<?php
namespace Tongcheng\Controller;
use Think\Controller;
class ShopController extends CommonController {
    public function index(){
        // $cate = array("car"=>"汽车模板", 'jiaoyu'=>"教育模板");

        if(IS_AJAX){
            $model = M("Shop");
            $map = array();
            $map['tp_shop.wid'] = session('wid');
            $map['is_pay'] = 1;

            $res['count'] = $model->where($map)->count();
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:10;
            $res['list'] = $model->where($map)->page("{$page},{$limit}")->select();
            foreach($res['list'] as $k=>$v){
                $tui = M("tui")->where(['wid'=>session('wid'),'aid'=>$v['shop_id'],"type"=>'shop'])->find();
                if(!$tui || !$tui['status']){
                    $res['list'][$k]['is_tui'] = 0;
                }else{
                    $res['list'][$k]['is_tui'] = 1;
                }
            }
            $this->ajaxReturn($res);
        }else{
            $this->display();
        }  
    }
    public function tui(){
        $r = tui("shop",I('id'),session('wid'),$_POST['status']);
        if($r){
            $this->success("操作成功！");
        }else{
            $this->error("网络忙，请稍后再试！");
        }
    }

    //申请生成小程序
    public function createmini()
    {
        $eq['shop_id'] = I('shop_id');
        $shop = M("shop")->where($eq)->find();
        if($shop['has_mini']){
            $data['code'] = 1;
            $data['msg'] = "小程序已生成，无需再次生成";
            $this->ajaxReturn($data);
            exit;
        }
        $new['type'] = I("type");
        $new['has_mini']  = 1;
        $r = M("Shop")->where($eq)->save($new);
        if($r){
            $data['code'] = 0;
            $data['msg'] = "申请成功，请等待审核";
            $this->ajaxReturn($data);
        }else{
            $data['code'] = 1;
            $data['msg'] = "网络繁忙，请稍后再试~";
            $this->ajaxReturn($data);
        }
    }
    //生成小程序
    public function mini()
    {
        $appid = C("OPEN_APPID");
        $eq['wid'] = session('wid');
        $eq['shop_id'] = $_GET['id'];
        if(IS_AJAX){
            if(I('session')){
                S("mini_shopid",null);
                exit;
            }
            //$r = M("Shop")->where($eq)->find();
            $sid = S("mini_shopid");
            if($sid && $sid != $eq['shop_id']){
                $data=array(
                    "msg" => "当前请求过多，请稍后再试！",
                    "code"=>3
                );
                $this->ajaxReturn($data);
            }
            //if($r>=0){
            //判断是否已经授权
            $mini = M('wechat')->where(array("shop_id"=>$eq['shop_id']))->find();
            if($mini){
                $data=array(
                    "url" => U("Index/fabu",array("shop_id"=>$eq['shop_id'])),
                    "code"=>1
                );
            }else{
                //锁住机制session判断
                S("mini_shopid",$eq['shop_id'],120);
                $pre_auth_code = $this->get_pre_auth_code();
                $redirect_uri = urlencode("https://www.58zltc.com");
                $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={$appid}&pre_auth_code={$pre_auth_code}&redirect_uri={$redirect_uri}";
                $data=array(
                    "url" => $url,
                    "code"=>2
                );
            }

            $this->ajaxReturn($data);
            //}
            /*else{
                $this->error("网络忙，请稍后再试！".M("Shop")->getLastSql());
            }*/
        }else {
            $info = M("Shop")->where($eq)->find();
            $types = array(
                array('title' => '通用模板', 'value' => ' '),
                array('title' => '汽车模板', 'value' => 'car'),
                array('title' => '教育模板', 'value' => 'jiaoyu'),
                array('title' => '建材模板', 'value' => 'jiancai')
            );
            $this->assign('info', $info);
            $this->assign('types', $types);
            $this->display();
        }
    }

    public function get_pre_auth_code(){
        $code = S("pre_auth_code{$_SESSION['uid']}");
        if($code){
            return $code;
        }
        $token = $this->get_component_access_token();
        if(!$token){
            return "";
        }

        $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
        $post_data = array(
            "component_appid"=>C("OPEN_APPID"));
        $json = json_encode($post_data);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['pre_auth_code']){
            S("pre_auth_code", $td['pre_auth_code'], $td['expires_in'] - 60);
            return $td['pre_auth_code'];
        }else{
            return "";
        }
    }

    private function get_component_access_token(){
        $token = S("component_access_token");
        if($token){
            return $token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";

        $post_data = array(
            "component_appid"=>C("OPEN_APPID"),
            "component_appsecret"=>C("OPEN_APPSECRET"),
            "component_verify_ticket"=>S("component_verify_ticket"));
        $json = json_encode($post_data);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['component_access_token']){
            S("component_access_token", $td['component_access_token'], $td['expires_in'] - 120);
            return $td['component_access_token'];
        }else{
            return false;
        }
    }

    public function add(){
        if(IS_POST){
            unset($_POST['file']);
            foreach ($_POST as $key => $value) {
                if(empty($value)){
                    $this->error('请填写全部信息！');
                }
            }
            $_POST['wid'] = session('wid');
            $_POST['is_pay'] = 1;
            $_POST['status'] = 1;
            if(M("Shop")->add($_POST)){
                $this->success("添加成功！");
            }else{
                $this->error("网络忙，请稍后再试！".$model->getLastSql());
            }
        }else{
            $cate_map['wid'] = session('wid');
            $cate_map['type'] = 'shop';
            $cate_map['pid'] = 0;

            $cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
            // dump($cates);
            foreach ($cates as $k => $v) {
                $cate_map['pid'] = $v['cid'];
                $cates[$k]['cid'] = $v['cid'];
                $cates[$k]['title'] =  $v['title'];
                $sub_cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
                if($sub_cates){
                    $cates[$k]['sub_cates'] = $sub_cates;
                }else{
                    $cates[$k]['sub_cates'][] = array('cid'=>0, 'title'=>'全部');
                }
            }
            $this->assign('cates',$cates);

            $map['wid'] = session('wid');
            $wechat = M("Wechat")->where($map)->find();
            $where['city_code'] = $wechat['city'];
            $city = M("City")->where($where)->find();
            $where1['pid'] = $city['id'];
            $site_arr2 = M("City")->where($where1)->getField("city_name",true);
            if($wechat['city'] == 0){

                $site_arr['name'] = '全国';
                $site_arr['sub_site'] = array('全国');
            }else{
                $site_arr['name'] = $city["city_name"];
                if(!$site_arr2){
                    $site_arr['sub_site'] = array("全辖区");
                }else{
                    $site_arr['sub_site'] = $site_arr2;
                }
            }
            $citys[] = $site_arr;
            $this->assign('citys',$citys);

            $this->display();
        }
    }

    public function type(){
        $eq['wid'] = session('wid');
        $eq['shop_id'] = $_GET['id'];
        if(IS_AJAX){
            $new['type'] = I("type");
            if(M("Shop")->where($eq)->save($new)){
                $this->success("修改成功！");
            }else{
                $this->error("网络忙，请稍后再试！".M("Shop")->getLastSql());
            }
        }else{
            $info = M("Shop")->where($eq)->find();

            $types = array(
                array('title'=>'通用模板', 'value'=>''),
                array('title'=>'汽车模板', 'value'=>'car'),
                array('title'=>'教育模板', 'value'=>'jiaoyu'),
                array('title'=>'建材模板', 'value'=>'jiancai')
            );
            $this->assign('info',$info);
            $this->assign('types',$types);

            $this->display();
        }
    }

    public function tong(){
        $model = M("Shop");
        $map['wid'] = session('wid');
        $map['shop_id'] = $_POST['id'];

        $new['status'] = 1;
        if($model->where($map)->save($new)){
            $this->success("上线成功！");
        }else{
            $this->error("网络忙，请稍后再试！".$model->getLastSql());
        }
    }

    public function renlingList(){
        if(IS_AJAX){
            $model = M("Renling");
            $map = array();
            $map['wid'] = session('wid');

            $res['count'] = $model->where($map)->count();
            $page = $_GET['page']?$_GET['page']:1;
            $limit = $_GET['limit']?$_GET['limit']:10;
            $res['list'] = $model->where($map)->page("{$page},{$limit}")->select();
            foreach ($res['list'] as $key => $value) {
                $eq['shop_id'] = $value['shop_id'];
                $res['list'][$key]['shop_name'] = M("Shop")->where($eq)->getField('name');
            }
            $this->ajaxReturn($res);
        }else{
            $this->display();
        }  
    }
    //后台审核商家
    public function audit_shop(){
        $map['wid'] = session('wid');
        $map['shop_id'] = I('shop_id');
        $new['status'] = 1;
        $r = M("shop")->where($map)->save($new);
        //echo M()->getLastSql();exit;
        if($r){
            //$arr = array('status'=>'1','msg'=>'审核成功!');
            //$this->ajaxReturn($arr);
            $this->success("审核成功！");
        }else{
            //$arr = array('status'=>'0','msg'=>'网络忙，请稍后再试！');
            //$this->ajaxReturn($arr);
            $this->error("网络忙，请稍后再试！");
        }
    }
    public function renling(){
        $model = M("renling");
        $map['wid'] = session('wid');
        $map['id'] = $_POST['id'];

        $new['status'] = 1;

        $info = $model->where($map)->find();
        $eq['shop_id'] = $info['shop_id'];

        $data['openid'] = $info['openid'];
        $data['tel'] = $info['tel'];
        $data['username'] = $info['username'];
        M("Shop")->where($eq)->save($data);
        if($model->where($map)->save($new)){
            $this->success("认领成功！");
        }else{
            $this->error("网络忙，请稍后再试！".$model->getLastSql());
        }
    }
}